<?php


namespace app\admin\controller;


use app\admin\common\library\FlowEngine;
use app\admin\model\Budget;
use app\admin\model\FlowInstance;
use app\admin\model\FlowNumber;
use app\admin\model\FlowTask;
use app\admin\model\Item;
use app\admin\model\JournaLevel;
use app\admin\model\WorkJournal;
use app\BaseController;
use app\Request;
use think\facade\Db;
use think\facade\View;

class Finishworkitem extends BaseController
{
    protected $model = null;
    protected $task = null;
    protected $flow = null;
    protected $currentNode = null;
    protected $nextNode = null;
    protected $scheme = null;
    protected $instance = null;
    protected $prefix = "";
    protected $adminModel = null;
    protected $number = null;
    protected $select = null;
    public function initialize()
    {
        parent::initialize();
        $this->task = new FlowTask();
        $this->instance = new FlowInstance();
        $this->scheme = new \app\admin\model\Scheme();
        $this->adminModel = new \app\admin\model\Admin();
        $this->number = new FlowNumber();
        $this->select = Db::name('view_workitem')->field('flowname')->distinct(true)->select();
        View::assign('select',$this->select);

    }


    //显示
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');


            $where = array();
            if ($request->has('instancecode') && !empty($request->get('instancecode'))) {
                $where[] = array("instancecode", "like", "%" . $request->get('instancecode') . "%");
            }
            if ($request->has('flowname') && !empty($request->get('flowname'))) {
                $where[] = array("flowname", "like", "%" . $request->get('flowname') . "%");
            }

            if ($request->has('nickname') && !empty($request->get('nickname'))) {
                $where[] = array("nickname", "like", "%" . $request->get('nickname') . "%");
            }
//            if ($request->has('createtime') && !empty($request->get('createtime'))) {
//                $where[] = array("createtime", "=", $request->get('createtime'));
//            }
//            if ($request->has('completedtime') && !empty($request->get('completedtime'))) {
//                $where[] = array("completedtime", "=", $request->get('completedtime'));
//            }
            $where[] = array("status", "=", 2);
            $where[] = array("receiveid", "=", $this->auth->id);

            $total = Db::name('view_workitem')
                ->where($where)
                ->order('createtime desc')
                ->count();

            $list = Db::name('view_workitem')
                ->where($where)
                ->order('createtime desc')
                ->page($page,$limit)->select()->toArray();

            foreach ($list as $key => $value) {
                if (strpos($value['comment'], '拒绝') !== false) {
                    $list[$key]['is_a'] = 1;
                } else {
                    $list[$key]['is_a'] = 2;
                }
            }
            return json(['code' => 200, 'msg' => '', 'total' => $total, 'data' => $list]);
        }
        return View::fetch();
    }

    //NEXT
    public function edit(\think\Request $request)
    {

        $journal_level = JournaLevel::select();
        $table = $request->param('table');
        $ids = $request->param('ids');
        $row = Db::name($table)->find($ids);
        if (!$row)
            return json(['code' => 400, 'url' => '', 'msg' => 'No Results were found(未找到结果)']);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                return json(['code' => 400, 'url' => '', 'msg' => 'You have no permission(你没有权限)']);
            }
        }
        $taskid = $request->param('taskid');

        $task = null;
        $mode = $request->param('mode');
        if ($mode == 'view') {
            $task = $this->task->where(['id' => $taskid])->find();
        } else {
            $task = $this->task->where(['id' => $taskid])->where('status', 2)->find();
        }
        if (!$task)
            return json(['code' => 400, 'url' => '', 'msg' => '找不到当前任务']);

        $schme = $this->scheme->find($task['flowid']);
        $instance = FlowInstance::find($task['instanceid']);
        $originator = \app\admin\model\Admin::find($instance['originator']);

        if ($task['from_table'] == "vacations") { //请假
            $model = \app\admin\model\Vacation::find($task['from_id']);
            if (empty($model)) {
                return "找不到该资源";
            }
            $model = \app\admin\model\Vacation::checkDetail($model['id']);
            if (preg_match("/([\x81-\xfe][\x40-\xfe])/", $model->corresponding, $match)) {
                //含有汉字
                $model['is_number'] = 1;
            } else {
                //不含有汉字
                $model['is_number'] = 2;
            }
            $src = "detail/vacation_detail";
        } else if ($task['from_table'] == "applies") { //申请
            $model = \app\admin\model\Applies::with(['typeName'])->find($task['from_id']);
            if (empty($model)){
                return "找不到该信息，请联系管理员";
            }
            if($model->typeName->name == "借款"){
                $money = Db::name('applies_money')->where('applies_id',$task['from_id'])->find();
                if (empty($model)){
                    return "找不到该信息，请联系管理员";
                }
                $money['dx'] = get_amount($money['jk_money']);
                $model['money'] = $money;
            }else if ($model->typeName->name == "用章"){
                $zhang = Db::name('applies_zhang')->where('applies_id',$task['from_id'])->find();
                if (empty($zhang)){
                    return "找不到该信息，请联系管理员";
                }
                $model['zhang'] = $zhang;
            }else if ($model->typeName->name == "用车"){
                $che = Db::name('applies_che')->where('applies_id',$task['from_id'])->select();
                if (empty($che)){
                    return "找不到该信息，请联系管理员";
                }
                $model['che'] = $che;
            }else if ($model->typeName->name == "采购"){
                $caigou = Db::name('applies_cg')->where('applies_id',$task['from_id'])->select();
                if (empty($caigou)){
                    return "找不到该信息，请联系管理员";
                }
                $model['caigou'] = $caigou;
            }else{
                $model="";
            }
            $src = "detail/applies_detail";
        } else if ($task['from_table'] == "journals") { //日志
            $model = WorkJournal::with('week')->find($task['from_id'])->toArray();
            if (empty($model)){
                return "找不到该信息，请联系管理员";
            }
            $src = "detail/journals_detail";
        } else if ($task['from_table'] == "projects") { //项目
            $model = Item::with('dept')->find($task['from_id']);
            if (empty($model)){
                return "找不到该信息，请联系管理员";
            }
            $src = "detail/projects_detail";
        } else if ($task['from_table'] == "budget") { //预算
            $model = Budget::with(['Budgets'=>['ProjectBudgetPlanConfig','ProjectBudgetTypeConfig']])->find($task['from_id']);
            if (empty($model)){
                return "找不到该信息，请联系管理员";
            }
            $zongjine = 0;
            if(count($model->Budgets->ProjectBudgetPlanConfig) > 0){
                foreach ($model->Budgets->ProjectBudgetPlanConfig as $key=>$value){
                    $zongjine+=$value['sum_of_money'];
                }
            }

            View::assign('zongjine', $zongjine);
            $src = "detail/budget_detail";
        }else if ($task['from_table'] == "overtime"){

            $model = \app\admin\model\Overtime::find($task['from_id']);
            if (empty($model)) {
                return "找不到该数据，请联系管理员";
            }
            $src = "detail/overtime_detail";
        }else{ //其他
            $model = "";
            $src = "";
        }
        $history = Db::name('flow_task')
            ->alias('main')
            ->join('admins admin', 'admin.id=main.receiveid', 'LEFT')
            ->where(['instanceid' => $task['instanceid'], 'main.status' => 2])
            ->field(["main.receiveid", "main.stepname", "main.comment", "admin.nickname", "main.completedtime"])
            ->order('main.createtime asc,main.completedtime asc')
            ->select();
        if ($request->isAjax()) {
            $row = Db::name($table)->find($ids);
            $data = $request->param();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    $this->model->validate($validate);
                }
                $this->flow = new FlowEngine($schme['flowcode']);
                $this->flow->next($taskid, $row, $data['comment']);
                return json(['code' => 200, 'url' => '', 'msg' => '审核成功']);
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        View::assign('journal_level', $journal_level);
        View::assign('table', $table);
        View::assign('ids', $ids);
        View::assign('task', $task);
        View::assign('flowCode', $schme['flowcode']);
        View::assign("history", $history);
        View::assign("mode", $mode);
        View::assign("instance", $instance);
        View::assign("row", $row);
        View::assign("originator", $originator);
        View::assign("auth", $this->auth);
        View::assign("model", $model);
        View::assign('schme', $schme);
        return View::fetch($src);
    }


    //借款单打印
    public function jkd(Request $request){
        $data  = $request->param();
        $res =  $list = Db::name('view_workitem')->field('instanceid,instancecode,nickname,from_id')
            ->where('id',$data['taskid'])->find();

        $jk = \app\admin\model\Applies::with(['money','admin'=>['dept']])->find($res['from_id'])->toArray();

        $jk['dx'] = get_amount($jk['money']['jk_money']);
        $jk['no'] = $res['instancecode'];
        $jk['bumen'] = $jk['admin']['dept']['name'] ?? $jk['group_name'];
        $history = Db::name('flow_task')
            ->alias('main')
            ->join('admins admin', 'admin.id=main.receiveid', 'LEFT')
            ->where(['instanceid' => $res['instanceid'], 'main.status' => 2])
            ->field(["main.receiveid", "main.stepname", "main.comment", "admin.nickname", "main.completedtime"])
            ->order('main.createtime asc,main.completedtime asc')
            ->select()->toArray();

        array_shift($history);
        array_pop($history);
        $data = [];
        foreach ($history as $key =>$value){
            if ($value['nickname'] !="超级管理员"){
                $data[] = $value;
            }
        }
        View::assign('data',$data);
        View::assign('jk',$jk);
        return View::fetch();
    }
}
